/*
Copyright (C) 2007 Kamal Singh.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

"Powered by http://backstage.bbc.co.uk"

NOTE: No graphics from this gadget cannot be reused in what so ever form.
*/

var channel = new Array();

channel[0] = {id:"OneXtra", title:"1Xtra", webLink:"http://www.bbc.co.uk/1xtra", link:"http://www.bbc.co.uk/1xtra/realmedia/1xtralive.ram", image:"channels\\OneXtra.png", desc:"BBC 1Xtra - new urban and black music, plus news, original in-house live music sessions, original live music concerts & music documentaries."};
channel[1] = {id:"BBCWrld", title:"BBC World Service", webLink:"http://www.bbc.co.uk/worldservice", link:"http://www.bbc.co.uk/worldservice/meta/tx/nb/live_news_au_nb.ram", image:"channels\\BBCWrld.png", desc:"International news, analysis and information from the BBC World Service."};
channel[2] = {id:"BBCAsian", title:"BBC Asian Network", webLink:"http://www.bbc.co.uk/asiannetwork", link:"http://www.bbc.co.uk/asiannetwork/rams/asiannetwork.ram", image:"channels\\BBCAsian.png", desc:"The BBC Asian Network is a BBC national radio station orientated towards British Asian life, culture and music in the UK and other topics from a British Asian perspective aimed at the under 35's from that community but aiming for a broader appeal among all interested in British Asian life whether Asian or not regardless of age."};
channel[3] = {id:"BBCRFiveX", title:"Five Live Sports Extra", webLink:"http://www.bbc.co.uk/fivelive/sportsextra", link:"http://www.bbc.co.uk/fivelive/live/surestream_sportsextra_int.ram", image:"channels\\BBCRFiveX.png", desc:"Sports Extra was set up by the team behind Five Live to bring you more sporting action. It's as simple as that. The station offers additional commentaries from the FA Barclays Premiership, Coca Cola League, Scottish Premier League and cup football - plus cricket, rugby, Formula One, tennis and golf."};
channel[4] = {id:"BBCROne", title:"BBC Radio 1", webLink:"http://www.bbc.co.uk/radio1", link:"http://www.bbc.co.uk/radio1/realaudio/media/r1live.ram", image:"channels\\BBCROne.png", desc:"BBC Radio 1 - youth oriented, mostly contemporary pop music (including Top 40 singles), plus news, original in-house live music sessions, original live music concerts & music documentaries."};
channel[5] = {id:"BBCRTwo", title:"BBC Radio 2", webLink:"http://www.bbc.co.uk/radio2", link:"http://www.bbc.co.uk/radio2/realmedia/fmg2.ram", image:"channels\\BBCRTwo.png", desc:"BBC Radio 2 - adult oriented entertainment, wide range of music - especially adult contemporary and middle of the road, also talk, comedy, plus news, original in-house live music sessions, original live music concerts & music documentaries."};
channel[6] = {id:"BBCRThree", title:"BBC Radio 3", webLink:"http://www.bbc.co.uk/radio3", link:"http://www.bbc.co.uk/radio3/ram/r3g2.ram", image:"channels\\BBCRThree.png", desc:"BBC Radio 3 - arts and high culture, special-interest music (classical, jazz, world music), plus news, original in-house live music sessions, original live music concerts & music documentaries."};
channel[7] = {id:"BBCRFour", title:"BBC Radio 4", webLink:"http://www.bbc.co.uk/radio4", link:"http://www.bbc.co.uk/radio4/realplayer/media/fmg2.ram", image:"channels\\BBCRFour.png", desc:"BBC Radio 4 - news, current affairs, arts, original in-house drama, original in-house first-run comedy, science, books and religion."};
channel[8] = {id:"BBCRFiveL", title:"BBC Radio 5", webLink:"http://www.bbc.co.uk/fivelive", link:"http://www.bbc.co.uk/fivelive/live/surestream_int.ram", image:"channels\\BBCRFiveL.png", desc:"BBC Radio Five Live is the BBC's radio service providing live BBC News, phone-ins, and sports commentaries. It is the principal radio station covering sport in the United Kingdom, broadcasting virtually all major sports events staged in the UK or involving British competitors."};
channel[9] = {id:"BBCSeven", title:"BBC 7", webLink:"http://www.bbc.co.uk/bbc7", link:"http://www.bbc.co.uk/bbc7/realplayer/dsatg2.ram", image:"channels\\BBCSeven.png", desc:"BBC 7 - classic comedy, drama, books, science fiction, fantasy and children's programmes."};
channel[10] = {id:"BBCSixMU", title:"BBC 6 Music", webLink:"http://www.bbc.co.uk/6music", link:"http://www.bbc.co.uk/6music/ram/dsatg2.ram", image:"channels\\BBCSixMU.png", desc:"BBC 6 Music - rock, funk, punk and reggae, plus news, original in-house live music sessions, original live music concerts & music documentaries."};

var itemList;
var API_URL = "http://www0.rdthdo.bbc.co.uk/cgi-perl/api/query.pl?";
var results;
var now = new Date();
var TIME_OFFSET = ( now.getTimezoneOffset() / 60 )*-1

realPlayer = RealPlayerEmbed.object;
//realPlayer.settings.volume = volume_control.value;

// timers
view.setInterval( updateCheck, 1000 * 60 * 3 );
view.setInterval( timeUpdate, 1000 );
view.setInterval( indicatorAnimation, 1000 );

var CHANNEL_NO = 0;
var ANIMATE_COUNTER = 0;

function volume_onchange() {
  if ( realPlayer == null )
    return;
  realPlayer.SetVolume( volume_control.value );
}

// Set the default for first run, other wise load the user selected option
function SetDefaultOptions() {
  if ( getStation() == "") {
    // if nothing is set then set channel 1 as the default
    setStation( 10 );
    getSchedule( channel[10].id );
    updateStaticInfo( 10 );
    onClickPlay();
  }
  else {  // otherwise load the user last played channel
    var _station = getStation();
    getSchedule( channel[_station].id );
    updateStaticInfo( _station );
    if ( getPlayerStatus() == "start" )
      onClickPlay();
    else
      onClickStop();
  }
}

// update the 'duration' label 
function timeUpdate() {
  duration.innerText = Math.round(realPlayer.GetPosition() / 1000) + "s";
  displayStatus();
}

// set user selected radio station
function setStation( station ) {
  options.PutValue( "stationNumber", station );
}

// returns user prefered radio station
function getStation() {
  return options.GetValue( "stationNumber" );
}

// set player status, like playing or stopped
function setPlayerStatus( status ) {
  options.PutValue( "playerStatus", status );
}

// returns player status
function getPlayerStatus() {
  return options.GetValue( "playerStatus" );
}

function onLoad() {
  SetDefaultOptions();
}

function updateCheck() {
  num = getStation();
  getSchedule( channel[num].id );
  updateStaticInfo( num );
}

function buttonHandler() {
  realPlayer.DoStop();
  if ( CHANNEL_NO == 10 ) {
    CHANNEL_NO = 0;
  }
  else {
    CHANNEL_NO = CHANNEL_NO + 1;
  }
  setStation( CHANNEL_NO );
  getSchedule( channel[CHANNEL_NO].id );
  updateStaticInfo( CHANNEL_NO );
  onClickPlay();
}

function updateStaticInfo( num ) {
	var index = channel[num];
	channelImage.src = index.image;
	channelLink.href = index.webLink;
	channelLink.tooltip = index.desc;
	realPlayer.SetSource(index.link);
}

function updateText() {
  nowTitle.innerText = results[0].title;
  nowTitle.tooltip = results[0].title;
  nowTime.innerText = results[0].start;
  nowTime.tooltip = results[0].start;
  nowSynopsis.innerText = results[0].synopsis;
  nowSynopsis.tooltip = results[0].synopsis;
}

function indicatorAnimation()	{
	if ( ANIMATE_COUNTER == 11 )
		ANIMATE_COUNTER = 0;
	else
		ANIMATE_COUNTER = ANIMATE_COUNTER + 1;
	indicator.src = "indicator\\indicator_large_" + ANIMATE_COUNTER + ".png";
}

function onClickPlay() {
	realPlayer.DoPlay();
	playButton.visible = false;
	stopButton.visible = true;
  	setPlayerStatus( "start" ); // store the player status
}

function onClickStop() {
	realPlayer.DoStop();
  	playButton.visible = true;
	stopButton.visible = false;
  	setPlayerStatus( "stop" );  // store the player status
}

function displayStatus() {
	if( realPlayer.GetPlayState() == 0 )
		status_message.innerText = "Stopped";
	else if( realPlayer.GetPlayState() == 1 )
		status_message.innerText = "Contacting";
	else if( realPlayer.GetPlayState() == 2 )
		status_message.innerText = "Buffering";
	else if( realPlayer.GetPlayState() == 3 )
		status_message.innerText = "Playing";
	else if( realPlayer.GetPlayState() == 4 )
		status_message.innerText = "Paused";
	else if( realPlayer.GetPlayState() == 5 )
		status_message.innerText = "Seeking";
}

// Request the schedule for the current channel using the BBC Web API
function getSchedule( cURL ) {
  var feedRequest = null;
  
  feedRequest = new XMLHttpRequest();
  try {
    var dMonth = now.getUTCMonth() + 1;
    if( dMonth < 10 )
      dMonth = "0" + dMonth;
    var dDate = now.getUTCDate();
    if( dDate < 10 )
      dDate = "0" + dDate;
    var hHour = now.getUTCHours();
    if( hHour < 10 )
      hHour = "0" + hHour;
    var hMin = now.getUTCMinutes();
    if( hMin < 10 )
      hMin = "0" + hMin;
    var gmtTime = now.getUTCFullYear() + "-" + ( dMonth ) + "-" + dDate + "T" + hHour + ":" + hMin + ":00" + "Z"; 
    var url = API_URL + "method=bbc.schedule.getProgrammes&channel_id=" + cURL + "&start=" + gmtTime + "&end=&limit=1&detail=schedule" + "&?sid=" + Math.random();
    debug.trace( url );
    feedRequest.open( "GET", url, true );
  } 
  catch ( e ) {
    debug.trace( e );
    // Catch invalid URLs
    feedRequest = null;
    return;
  }
  
  // Set the callback for when the downloading is completed (or failed)
  feedRequest.onreadystatechange = onFeedLoad;
  
  // Start the download
  try {
    feedRequest.send();
  }
  catch ( e ) {
    // Catch errors sending the request
    feedRequest = null;
    return;
  }
  
  function onFeedLoad() {
    // Verify that the download completed
    if ( feedRequest.readyState != 4 )
      return;

    // Verify that the download was successful
    if ( feedRequest.status != 200 ) {
      debug.trace( "download failed" );
      feedRequest = null;
      return;
    }

    var doc = new DOMDocument();
    doc.loadXML( feedRequest.responseText );
    var elem = doc.getElementsByTagName( "programme" );
    results = null;
    results = [];
    var title, synopsis, start;
    if ( elem != null && elem.length > 0 ) {
      for ( var z = 0; z < elem.length; z++ ) {        
        title = elem[z].getAttribute( "title" );
        debug.trace( title );
        for ( var node = elem[z].firstChild; node != null; node = node.nextSibling ) {
          if ( node.nodeName == "synopsis" ) {
            try {
              synopsis = node.firstChild.nodeValue;debug.trace( synopsis );
            }            	
            catch ( e ) {
              synopsis = "error";
            }
          }
          if ( node.nodeName == "start" ) {
            try {
              start = node.firstChild.nodeValue;
              start = convertDate( start );
            }            	
            catch ( e ) {
              start = "2007-07-10T23:00:00Z";
            }
          }
          results[z] = {synopsis:synopsis, title:title, start:start};
        }
      }
    }
    feedRequest = null;
    updateText();
  }
}

// Formats date standard string into human-readable form
// e.g. 2007-07-11T22:40:00Z
function convertDate( str ) {
  var timeStr = "";
	var startPos = str.indexOf( "T", 0 );
	
	if ( TIME_OFFSET != 0 ) {
    var hourStr = str.substr( startPos + 1, 2 );
    var hour = stringToNumber( hourStr );
    timeStr = "" + hour + str.substr( startPos + 3, 8 );
  }
  else {
	  timeStr = str.substr( startPos + 1, 10 );
  }
	debug.trace(timeStr);
  var endPos = timeStr.indexOf( ":", 3 );
  timeStr = timeStr.substr( 0, endPos );		  

  return timeStr;
}

// translate a string to a number
function stringToNumber(str) {
  var num = 0;
	for ( var i = 0; i<str.length; i++ )
	  num += ( str.charCodeAt( i ) - 48 ) * Math.pow( 10, ( str.length - i - 1 ) );
  return num;
}